<?php

use App\Weixin\Models\WeixinUserModel;

/**
 * 友好的时间显示
 * @param int $sTime 待显示的时间
 * @param string $type 类型. normal | mohu | full | ymd | other
 * @param string $alt 已失效
 * @return string
 */
function friendlyDate($sTime, $type = 'normal', $alt = 'false')
{
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if ($type == 'normal') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';    //by yangjs
            } else {
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
            //今天的数据.年份相同.日期相同.
        } elseif ($dYear == 0 && $dDay == 0) {
            //return intval($dTime/3600)."小时前";
            return '今天' . date('H:i', $sTime);
        } elseif ($dYear == 0) {
            return date("m月d日 H:i", $sTime);
        } else {
            return date("Y-m-d H:i", $sTime);
        }
    } elseif ($type == 'mohu') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';    //by yangjs
            }
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dDay <= 30) {
            return intval($dDay / 7) . '周前';
        } elseif ($dDay > 30) {
            return intval($dDay / 30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    } elseif ($type == 'full') {
        return date("Y-m-d  H:i:s", $sTime);
    } elseif ($type == 'ymd') {
        return date("Y-m-d", $sTime);
    } elseif ($type == 'short') {
        //一天内 H:i,超过一天 m-d
        if ($dDay == 0) {
            return date("H:i", $sTime);
        } elseif ($dDay > 0) {
            return date("m-d", $sTime);
        }
    } else {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚';    //by yangjs
            }
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dYear == 0) {
            return date("m-d", $sTime);
        } elseif ($dYear > 0) {
            return date("Y-m-d H:i:s", $sTime);
        } else {
            return date("Y-m-d H:i:s", $sTime);
        }
    }
}


/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function getClientIp($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * 根据用户ID获取用户名
 * @param  integer $uid 用户ID
 * @return string       用户名
 */
function get_username($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        $user = session('lqwsys_auth');
        return $user["username"];;
    }

    /**
     * @var $iMember App\Admin\Contracts\MemberInterface
     */
    $iMember=app()->make(App\Admin\Contracts\MemberInterface::class);
    $name=$iMember->getAccountByUid($uid);
    return $name;
}
function get_nickname($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        $user = session('lqwsys_auth');
        return $user["nickname"];;
    }
    /**
     * @var $iMember App\Admin\Contracts\MemberInterface
     */
    $iMember=app()->make(App\Admin\Contracts\MemberInterface::class);
    $info=$iMember->getMemberInfo(["uid"=>$uid]);
    return $info["nickname"]??"";
}
/**
 * 返回登陆后用户uid
 * @return int
 * @author 林子彦  <278805354@qq.com>
 */
function is_login() {
    $user = session('lqwsys_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('lqwsys_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

/**
 * 记得密码参证
 * @return int|string
 */
function iscookie_remember(){
    $adminUid= \Illuminate\Support\Facades\Cookie::get("admin_uid");
    $adminUsername= \Illuminate\Support\Facades\Cookie::get("admin_username");
    $adminNickname= \Illuminate\Support\Facades\Cookie::get("admin_nickname");
    $adminLogo= \Illuminate\Support\Facades\Cookie::get("admin_logo");
    $lqwsys_auth_sign= \Illuminate\Support\Facades\Cookie::get("lqwsys_auth_sign");
    $auth = array(
        'uid' =>$adminUid,
        'username' =>$adminUsername,
        'nickname' => $adminNickname,
        'logo' => $adminLogo
    );
    return $lqwsys_auth_sign == data_auth_sign($auth) ? $adminUid : 0;
}
/**
 * 密码加密
 * @return int
 * @author 林子彦  <278805354@qq.com>
 */
function lqw_ucenter_md5($str, $key = 'lqwUCenter') {
    return '' === $str ? '' : md5(sha1($str) . $key);
}
/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @author 林子彦  <278805354@qq.com>
 * @return string       签名
 */
function data_auth_sign($data) {
//数据类型检测
    if (!is_array($data)) {
        $data = (array) $data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}
/**
 * 判断是否是超级管理员
 * @author 林子彦  <278805354@qq.com>
 * @return boolean
 */
function is_administrator($uid = null){

    $uid = is_null($uid) ? is_login() : $uid;

    //判断
    return $uid && (intval($uid) === config('lzy.USER_ADMINISTRATOR'));
}

/**
 * 树组装
 * @author 林子彦  <278805354@qq.com>
 * @param type $list
 * @param type $pk
 * @param type $pid
 * @param type $child
 * @param type $root
 * @return type
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 记录行为日志，并执行该行为的规则
 * @param string $action 行为标识
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @return boolean
 * @author lzy
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null){
    //参数检查
    if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id =!empty(UID)?0:UID;
    }
    $iAction=app()->make(\App\Admin\Contracts\ActionInterface::class);
    $actionInfo=$iAction->getActionInfo(["name"=>$action]);
    if(empty($actionInfo)){
        return "查无此记录类型";
    }
    if($actionInfo->status != 1){
        return '该行为被禁用或删除';
    }
    $now_time=time();
    //插入行为日志
    $data['action_id']      =   $actionInfo->id;
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(getClientIp());
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   $now_time;

    //解析日志规则,生成日志备注
    if(!empty($actionInfo->log)){
        if(preg_match_all('/\[(\S+?)\]/', $actionInfo->log, $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   $now_time;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>$now_time);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] =   str_replace($match[0], $replace, $actionInfo->log);
        }else{
            $data['remark'] =   $actionInfo->log;
        }
    }else{
        //未定义日志规则，记录操作url
        $data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];
    }
    $iAction->saveActionLogData($data);
    if(!empty($actionInfo->rule)){   //规则操作-----执行行为---放到队列中执行(队列)
        $param=array();
        $param['user']    =   $user_id;    //操作者
        $param['record']  =   $record_id;   //记录id
        $param['model']   =   $model;     //模型
        $param['action_id']   =   $actionInfo->_id;  //操作的id
        /**
         * 例子
         * $param['user']    =   1;
        $param['record']  =   2;
        $param['model']   =   "quiz";
        $param["action_id"] = "5b1e2c7ab371e90760006660";
        $iAction->executeAction("App\Base\Contracts\ActionInterface",$param);
         */
       // $res = $iAction->executeAction($actionInfo->rule,$param);
    }
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}
// 不区分大小写的in_array实现
function in_array_case($value,$array){
    return in_array(strtolower($value),array_map('strtolower',$array));
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}


/**
 * @author 林子彦
 */
if(!function_exists ('get_config_param_value')){
    function get_config_param_value($key){ //获取配置参娄
        $iConfig=app()->make(\App\Admin\Contracts\ConfigInterface::class);
        $info=$iConfig->getConfigInfo(["name"=>$key]);
        return $info["value"]??'';
    }
}
if(!function_exists ('set_config_param_value')){
    function set_config_param_value($key,$value){ //设置配置参娄
        $iConfig=app()->make(\App\Admin\Contracts\ConfigInterface::class);
        $info=$iConfig->setConfigValue(["name"=>$key],["value"=>$value]);
        return $info;
    }
}
/**
 * 处理带Emoji的数据，type=0表示写入数据库前的emoji转为HTML，为1时表示HTML转为emoji码
 * @param $msg
 * @param int $type
 * @return false|mixed|null|string|string[]
 */
function deal_emoji($msg, $type = 1) {
    if ($type == 0) {
        $msg = urlencode ( $msg );
        $msg = json_encode ( $msg );
    } else {

        $msg = preg_replace_callback ( "#\\\u([0-9a-f]+)#i", function ($r) {
            return iconv ( 'UCS-2', 'UTF-8', pack ( 'H4', '\\1' ) );
        }, $msg );
        $msg = urldecode ( $msg );
        // $msg = json_decode ( $msg );
        // dump($msg);
        $msg = str_replace ( '"', "", $msg );
    }

    return $msg;
}


function get_wxusername_by_uid($uid){
    if(empty($uid)){
        return "无";
    }
   return  WeixinUserModel::query()->where("uid",$uid)->value("truename");
}